package com.shawn.recommend.listener;

import com.alibaba.fastjson.JSON;
import com.shawn.model.mongo.Movement;
import com.shawn.model.mongo.MovementScore;
import com.shawn.model.mongo.Video;
import com.shawn.model.mongo.VideoScore;
import org.apache.logging.log4j.util.Strings;
import org.bson.types.ObjectId;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.Objects;

/**
 * @author shawn
 * @date 2022年 11月 11日 15:56
 */
@Component
public class RecommendVideoListener {


    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 动态行为监听
     *
     * @param message 消息
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "touch.video.queue"
                    ,durable = "true"),//持续监听
            exchange = @Exchange(name = "touch.log.exchange",type = ExchangeTypes.TOPIC),
            key = {"log.video"}
    ))
    public void ListenUserLog(String message){
        //解析数据
        Map map = JSON.parseObject(message, Map.class);
        //1、获取数据
        Long userId = Long.parseLong((String) map.get("userId"));
        String logTime = (String) map.get("logTime");
        String videoId = (String) map.get("busId");
        String type = (String) map.get("type");
        if (Strings.isEmpty(videoId)){
            return;
        }
        //根据动态id查找动态
        Video video = mongoTemplate.findById(new ObjectId(videoId), Video.class);
        if (!Objects.isNull(video)){
            VideoScore vs = new VideoScore();
            vs.setUserId(userId);
            vs.setDate(System.currentTimeMillis());
            vs.setVideoId(video.getVid());
            vs.setScore(getVideoScore(type));
            //保存该数据
            mongoTemplate.save(vs);
        }
    }

    private static Double getVideoScore(String type) {
        //0301为发小视频，0302为小视频点赞，0303为小视频取消点赞，0304为小视频评论
        Double score = 0d;
        switch (type) {
            case "0301":
                score=2d;
                break;
            case "0302":
                score=5d;
                break;
            case "0303":
                score = -5d;
                break;
            case "0304":
                score = 10d;
                break;
            default:
                break;
        }
        return score;
    }
}
